// src/pages/personal/widgets/updateNickname/index.tsx
import styles from "@pages/personal/styles/styles.module.less";
import Header from "@shared/header";
import GeekIcon from "@shared/geekIcon";
import React from "react";
import { SlideRef } from "@shared/slide";

import { useEffect, useState } from "react";
import { useUpdateProfileMutation } from "@service/user";
import Loading from "@shared/loading";
import toast from "react-hot-toast";


interface Props {
    name: string;
    slideRef: React.RefObject<SlideRef | null>;
}

export default function UpdateNickname({ name, slideRef }: Props) {
    // 用于保存用户在文本框中输入的昵称
    const [nickname, setNickname] = useState(name);
    // 用于修改用户昵称
    const [updateProfile, { isLoading, isSuccess }] = useUpdateProfileMutation();

    // 监听修改成功
    useEffect(() => {
        if (isSuccess) {
            toast.success("用户昵称修改成功");
            slideRef.current?.close();
        }
    }, [isSuccess, slideRef]);

    return (
        <div className={styles.content}>
            <Header
                title={"编辑昵称"}
                left={
                    <GeekIcon
                        type={"iconfanhui"}
                        className={styles.icon}
                        onClick={slideRef.current?.close}
                    />
                }
                right={
                    <button
                        onClick={() => updateProfile({ name: nickname })}
                        className={styles.submit}
                    >
                        提交
                    </button>
                }
            />
            <form>
                <input value={nickname} onChange={(event) => setNickname(event.target.value)} />
            </form>
            {isLoading && <Loading />}
        </div>

    );
}
